//
//  FirstVC.m
//  夺宝吧
//
//  Created by xiaocai on 15/6/15.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//yyyy-MM-dd HH:mm:ss.fffffff
#import "FirstVC.h"
#import "FirstVCHeader.h"
#import "FirstCell.h"
#import "JSBadgeView.h"
#import "ProductModel.h"
#import "AppDelegate.h"
#import "MJRefresh.h"
#import "WYPublicWeb.h"
#import "PdcDetailVC.h"
#import "SeachVC.h"
#import "NoDataView.h"
#import "MFSideMenu.h"
#import "WYBase64Fun.h"

//首页单例
@interface FirstVC ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    //瀑布流视图
    UICollectionView *_collectionView;
    //当前页数
    int _currentPage;
    NSString *_currentFilter;
    //数据源
    NSMutableArray *_data;
    //圆角通知
    JSBadgeView *badgeView;
    
    //设置瀑布流的头
    FirstVCHeader *_firstVCHeader;
    
}



@property (nonatomic , strong) UIAlertView *alertView;

@property (nonatomic ,assign) BOOL isModelAlertView;

@end

@implementation FirstVC

// 获取首页的单例方法
+ (FirstVC *)shareFirstVC
{
    static FirstVC *staticVC = nil;
    
   static  dispatch_once_t once;
    dispatch_once(&once, ^{
        staticVC = [[FirstVC alloc]init];
    });
    return staticVC;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self loadAllData];
}

- (void)loadAllData{
    //每一次出现时超过30秒刷新
//    NSDate *dateNow = [NSDate date];
//    NSTimeInterval nowTime = [dateNow timeIntervalSince1970];
//    NSLog(@"%f %f",nowTime,nowTime-self.lastFreshDate);
//    if ((nowTime - self.lastFreshDate)> TIMER_COUNT ){
//        [self timerUpdate];
//    }
    //程序启动的时候第一次刷新
    if (self.firstFlag || (_data.count == 0)) {
        [self timerUpdate];
    }
    
    if (self.isCheckServer){
        [self performSelector:@selector(checkServer) withObject:nil afterDelay:1.0f];
        
        [_firstVCHeader startRequestForNews];
        
        self.isCheckServer = NO;
        
    }
    self.firstFlag = NO;
}
#pragma mark - 检测服务器是否在维护
- (void) checkServer{
    
    NSString *base64params = [WYBase64Fun base64StringFromText:@"unionId=2|channelId=2"];
    [WYRequest startPostForTongJiWithUrlStR:[NSString stringWithFormat:@"%@%@?param=%@",DBB_YX_IP,CHECK_SERVER,base64params] Parameters:nil successBlock:^(NSDictionary *dic) {
        
        NSDictionary *data = dic[@"data"];
        NSNumber *ret = dic[@"ret"];
        if ([ret isEqualToNumber:[NSNumber numberWithInt:0]]){
            NSNumber *isOpen = data[@"open"];
            NSString *title = data[@"title"];
            NSString *content = data[@"content"];
            NSNumber *isClose = data[@"winClose"];
            
            if ([isOpen isEqualToNumber:[NSNumber numberWithInt:1]]){
                
                BOOL isModel = NO;
                NSString *cancelStr = nil;
                if ([isClose isEqualToNumber:[NSNumber numberWithInt:1]]){
                    cancelStr = @"确定";
                    isModel = NO;
                }
                else{
                    cancelStr = nil;
                    isModel = YES;
                }
                
                if (self.alertView == nil ){
                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:title message:content delegate:self cancelButtonTitle:cancelStr otherButtonTitles:nil];
                    self.alertView = alertView;
                    self.isModelAlertView = isModel;
                    [alertView show];
                }
                if (self.alertView != nil && (isModel != self.isModelAlertView)){
                    [self.alertView dismissWithClickedButtonIndex:0 animated:NO];
                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:title message:content delegate:self cancelButtonTitle:cancelStr otherButtonTitles:nil];
                    self.alertView = alertView;
                    self.isModelAlertView = isModel;
                    [alertView show];
                }
                
            }
            else{
                if (self.alertView != nil){
                    [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
                    self.alertView = nil;
                }
            }
            
        }
        
    }
    failedBlock:^{
                                    
    } needLog:NO];
    
}

#pragma mark - 检查是否维护时alertView的代理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0){
        self.alertView = nil;
    }
}

#pragma mark - 定时器刷新
- (void)timerUpdate{
    
    //记录最后刷新的时间
    NSDate *dateNow = [NSDate date];
    self.lastFreshDate = [dateNow timeIntervalSince1970];
    
    [_collectionView headerBeginRefreshing];
    [_firstVCHeader startRequestForData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //延时请求服务器是否在维护
    self.isCheckServer = YES;
    
    //出事化当前时间
    NSDate *dateNow = [NSDate date];
    self.lastFreshDate = [dateNow timeIntervalSince1970];
    //初始化计时器
//    self.timer = [NSTimer timerWithTimeInterval:TIMER_COUNT target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
//    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    //
    self.freshCount = 0;
    self.firstFlag = YES;
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    //初始化数据源
    _data = [NSMutableArray array];
    //首页置1
    _currentPage = 1;
    _currentFilter = @"-10";
    //加载导航条
    [self loadCustomNaviBar];
    //加载瀑布流控件
    [self loadCollectionView];
    
}
//加载导航条
- (void)loadCustomNaviBar
{
    UIView *naviBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WYMWITH, 20+44)];
    naviBar.backgroundColor = QBB_RED_COLOR;
    
    //标题
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 25)];
    titleLab.center = CGPointMake(WYMWITH/2, 42);
    titleLab.text = @"夺宝吧";
    titleLab.font = [UIFont systemFontOfSize:TITLE_SIZE];
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.textColor = [UIColor whiteColor];
    [naviBar addSubview:titleLab];
    

    [self.view addSubview:naviBar];
    //菜单按钮
    UIButton *meauBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    meauBtn.frame = CGRectMake(10, 30,  30, 20);
    [meauBtn setImage:[UIImage imageNamed:@"icon_menu_sidebar"] forState:UIControlStateNormal];
    //    [meauBtn setImage:[UIImage imageNamed:@"icon_mail_press"] forState:UIControlStateHighlighted];
    [meauBtn addTarget:self action:@selector(meauBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
    [naviBar addSubview:meauBtn];
    
    //搜索按钮
    UIButton *morebtn = [UIButton buttonWithType:UIButtonTypeCustom];
    morebtn.frame = CGRectMake(WYMWITH - 40, 25,  30, 30);
    [morebtn setImage:[UIImage imageNamed:@"icon_search_normal"]  forState:UIControlStateNormal];
    [morebtn setImage:[UIImage imageNamed:@"icon_search_press"]  forState:UIControlStateHighlighted];
    [morebtn addTarget:self action:@selector(moreBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
    [naviBar addSubview:titleLab];
    [naviBar addSubview:morebtn];
    [self.view addSubview:naviBar];
}
- (void)meauBtnOnClick
{
    //展开左菜单
    [self.menuContainerViewController toggleLeftSideMenuCompletion:^{
        AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
        [myDelegate.leftMenuVC requestForData];
    }];
}
//更多按钮的监听事件
- (void)moreBtnOnClick
{
    SeachVC *seachVC = [[SeachVC alloc]init];
    [self.navigationController presentViewController:seachVC animated:YES completion:nil];
}

////开奖规则按钮的监听事件
//- (void)roleBtnOnCLick
//{
//    WYPublicWeb *web = [[WYPublicWeb alloc]init];
//    web.urlStr = [NSString stringWithFormat:@"%@%@",DBB_IP,@"/api/ApiMisc/article&id=dbba_gamerules"];
//    web.mtitle = @"开奖规则";
//    [self.navigationController pushViewController:web animated:YES];
//}
/***********
 *加载瀑布流控件
 ************/
- (void)loadCollectionView
{
    //初始化瀑布流
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 20+44, self.view.frame.size.width, self.view.frame.size.height-20-49-44) collectionViewLayout:layout];
    //设置代理
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
   
    //注册cell
    UINib *nib = [UINib nibWithNibName:@"FirstCell" bundle:nil];
    [_collectionView registerNib:nib forCellWithReuseIdentifier:@"cell"];
    
    //设置瀑布流的头
    _firstVCHeader = [[[NSBundle mainBundle]loadNibNamed:@"FirstVCHeader" owner:self options:nil]lastObject];
    _firstVCHeader.frame = CGRectMake(_firstVCHeader.frame.origin.x, _firstVCHeader.frame.origin.y, WYMWITH, _firstVCHeader.frame.size.height);
    _firstVCHeader.father = self;
    [layout setHeaderReferenceSize:CGSizeMake(WYMWITH, _firstVCHeader.frame.size.height+1)];
    [_collectionView addSubview:_firstVCHeader];
    [self.view addSubview:_collectionView];
    // 2.集成刷新控件
    [self addHeader];
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_collectionView addFooterWithTarget:self action:@selector(footerRereshing)];
}
- (void)footerRereshing
{
    self.isPullUpFresh = YES;
    _currentPage++;
    [self startRequestForData];
}
-(void)addHeader
{
    __unsafe_unretained typeof(self) vc = self;
    __unsafe_unretained typeof(NSMutableArray) *bData = _data;
    __unsafe_unretained typeof(FirstVCHeader) *header = _firstVCHeader;
    // 添加下拉刷新头部控件
    [_collectionView addHeaderWithCallback:^{
//        [bData removeAllObjects];
        vc.isPullDownFresh = YES;
        _currentPage = 1;
        // 进入刷新状态就会回调这个Block
        [vc startRequestForData];
        
        [header startRequestForData];
        
        [header startRequestForNews];
    } dateKey:@"collection"];
    
    
    
    
}
//请求网络数据
- (void)startRequestForData
{
    [WYPublic addHudToWindow];
    self.view.userInteractionEnabled = NO;
    NSDictionary *params = @{@"order":_currentFilter,@"filter":@"20",@"num":@"20",@"page":[NSNumber numberWithInt:_currentPage]};
    
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,HOT_URL] Parameters:params successBlock:^(NSDictionary *dic) {
//        [WYPublic removeHudToWindow];
        self.freshCount = 0;
        
        if (self.isPullDownFresh){ //下拉清空数据
            [_data removeAllObjects];
            self.isPullDownFresh = NO;
        }
        if (self.isPullUpFresh){  //下拉加载不清空数据
            self.isPullUpFresh = NO;
        }
        
        if (_firstVCHeader.isFilterFresh){  //选择性刷新清空数据
            [_data removeAllObjects];
            _firstVCHeader.isFilterFresh = NO;
        }
        
        NSNumber *ret = dic[@"ret"];
       
        if ([ret integerValue] == 0) {
//            if (_currentPage == 1 && _data.count>0) {
//                return ;
//            }
        
            NSArray *pdcs = dic[@"data"][@"list"];
            for (NSDictionary *pdc in pdcs) {
                ProductModel *model = [[ProductModel alloc]init];
                model.pdc_id = pdc[@"id"];
                model.pdc_title = pdc[@"title"];
                model.pdc_qishu = pdc[@"qishu"];
                model.pdc_sid = pdc[@"sid"];
                model.pdc_sub_title = pdc[@"title2"];
                model.pdc_desc = pdc[@"description"];
                model.pdc_people_indeed = pdc[@"zongrenshu"];
                model.pdc_people_now = pdc[@"canyurenshu"];
                model.pdc_people_left = pdc[@"shenyurenshu"];
                model.pdc_img_path = pdc[@"thumb_url"];
                model.is_locked = pdc[@"is_locked"];

                [_data addObject:model];
                
            }
            if(_data.count > 0){
                [_collectionView reloadData];
                for (UIView *v in _collectionView.subviews) {
                    if (v.tag == 12121) {
                        [v removeFromSuperview];
                    }
                }
            }
            // 结束刷新
            [_collectionView headerEndRefreshing];
        }else{
            if(_data.count == 0){
                [self addNODataView];
            }
        }
        // 结束刷新
        [_collectionView headerEndRefreshing];
        [_collectionView footerEndRefreshing];
        [WYPublic removeHudToWindow];
        self.view.userInteractionEnabled = YES;

    } failedBlock:^{
        if(_data.count > 0){
            for (UIView *v in _collectionView.subviews) {
                if (v.tag == 12121) {
                    [v removeFromSuperview];
                }
            }
        }else{
            [self addNODataView];
        }
        // 结束刷新
        [_collectionView headerEndRefreshing];
        [WYPublic removeHudToWindow];
        self.view.userInteractionEnabled = YES;
        [_collectionView footerEndRefreshing];
    } needLog:NO];
}
//没有数据默认填充的控件
- (void)addNODataView{

    if (self.freshCount < 3){
        self.freshCount ++;
        
        AppDelegate *delegate =    [UIApplication sharedApplication].delegate;
        if (delegate.isLaunch){
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self startRequestForData];
            });
        }
        
    }else{
    
        NoDataView *nodateView = [[[NSBundle mainBundle]loadNibNamed:@"NoDataView" owner:self options:nil]lastObject];
        nodateView.tag = 12121;
        nodateView.frame = CGRectMake(0, 0, WYMWITH, _collectionView.contentSize.height);
        nodateView.isMineFlag = NO;
        nodateView.title = @"获取数据失败!";
        [_collectionView addSubview:nodateView];
        
    }
}
#pragma mark - 瀑布流控件的协议方法
//定义返回多少段
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//定义有多少个元素显示
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _data.count;
}

//每个元素上显示的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    FirstCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (_data.count>0) {
        //获取当前数据模型
        ProductModel *model = _data[indexPath.row];
        //填充cell
        [cell fillCellWithModel:model];
        cell.cltView = _collectionView;
        
    }
    //    cell.selectedBackgroundView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    return cell;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
     AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    return CGSizeMake(160*myDelegate.autoSizeScaleX, 190*myDelegate.autoSizeScaleY);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
   //保存至兴趣记录
    if (_data.count > 0) {
        ProductModel *currentModel = _data[indexPath.row];
        WYShopCarModel *model = [[WYShopCarModel alloc]init];
        model.car_id = currentModel.pdc_id;
        model.car_new_id = currentModel.pdc_sid;
        model.name = currentModel.pdc_title;
        model.imgPath = currentModel.pdc_img_path;
        model.count = 1;
        [[WYDataBase sharedDataBase]insertPdcToIntrestCarWithModel:model];
        //跳往商品详情
        PdcDetailVC *detailVC = [[PdcDetailVC alloc]init];
        detailVC.pdc_id = currentModel.pdc_id;
        [self.navigationController pushViewController:detailVC animated:YES];
        self.firstFlag = NO; //push 返回时候不刷新数据
    }
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //    WYGoodsModel *model = _data[indexPath.row];
    
    return YES;
}



//改变筛选条件
- (void)changeupdateWithId:(NSString *)cid
{
//    [_data removeAllObjects];ƒ
    _currentFilter = cid;
    _currentPage = 1;
    [self startRequestForData];
    if (_collectionView.contentOffset.y >= 337.0) {
        [UIView animateWithDuration:0.2 animations:^{
            _collectionView.contentOffset=CGPointMake(0, 337);
        }];
    }
}
/********************头不动的处理********************/
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView.contentOffset.y > 337.0){
        _firstVCHeader.frame = CGRectMake(_firstVCHeader.frame.origin.x, scrollView.contentOffset.y - 337, _firstVCHeader.frame.size.width, _firstVCHeader.frame.size.height);
    }else{
        _firstVCHeader.frame = CGRectMake(_firstVCHeader.frame.origin.x, 0, _firstVCHeader.frame.size.width, _firstVCHeader.frame.size.height);
    }
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
//    [WYPublic removeHudToWindow];

//    //停止请求
//    [WYRequest stopAllRequest];
//    // 结束刷新
//    [_collectionView headerEndRefreshing];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    
    
    self.view = nil;
    
}
-(void)dealloc{
    
    NSLog(@"FirstVC dealloc");
}
@end
